package com.example.demo.filter;

import com.alibaba.fastjson.JSON;
import com.example.demo.jwt.Jwt;
import com.example.demo.jwt.TokenState;
import com.example.demo.result.Result;
import com.example.demo.result.ResultCode;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * toekn校验过滤器，所有的API接口请求都要经过该过滤器(除了登陆接口)
 *
 *
 */
@Component
public class UrlFilter implements Filter {


    @Override
    public void doFilter(ServletRequest argo, ServletResponse arg1,
                         FilterChain chain ) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) argo;
        HttpServletResponse response=(HttpServletResponse) arg1;
        String url = request.getRequestURI();
        response.setHeader("Access-Control-Allow-Origin", "*");
        if(url.endsWith("/user/login")||url.endsWith("/swagger-ui.html")||url.startsWith("/webjars")||url.startsWith("/swagger-resources")||url.startsWith("/v2")||url.startsWith("/file/download")){
            //登陆接口不校验token，直接放行
            chain.doFilter(request, response);
            return;
        }
        //从请求头中获取token
        String token=request.getHeader("auth-token");
        JSONObject resultMap= Jwt.validToken(token);
        TokenState state= TokenState.getTokenState(resultMap.get("state").toString());
        switch (state) {
            case VALID:
                // 档案信息位置信息（添加方式为POST）
                if(request.getMethod().equals("POST")){
                    // 保存档案信息位置
//                    UserUtils.setArchiveLocation(request.getHeader("archiveLocation"));
                }
                //取出payload中数据,放入到request作用域中
                request.setAttribute("data", resultMap.get("data"));
                //放行
                chain.doFilter(request, response);
                break;
            case EXPIRED:
            case INVALID:
                JSONObject outputMSg=new JSONObject();
                outputMSg.put("msg", false);
                outputMSg.put("message", "您的token不合法或者过期了，请重新登陆");
                output(JSON.toJSONString(Result.failure(ResultCode.USER_LOGIN_TOKEN_ERROR,outputMSg)), response);
                break;
        }
    }


    public void output(String jsonStr,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8;");
        PrintWriter out = response.getWriter();
//		out.println();
        out.write(jsonStr);
        out.flush();
        out.close();

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
